import { defineStore } from 'pinia';
import { goodStorage } from '@/utils';
import { confInfo, loginByPwd } from '@/api/login';
import { selfInfo, userInfo } from '@/api/user';
import { getURL, getURLParameters } from '@/utils/tools';
export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    dataUser:goodStorage.get('dataUser', ''), 
    isType:goodStorage.get('isType', ''),
    confige:goodStorage.get('configeInfo', ''),
    token: goodStorage.get('token', ''),
    routerInfo:goodStorage.get('routerInfo', ''),
    storeInfo:goodStorage.get('storeInfo', ''),
    orderStatus:{0:'全部',3:'待发货',4:'待签收',5:'待核销',1:'已完成',7:'待售后',8:'售后中',9:'售后完成'},
  }),
  getters: {
    getisType: (state): boolean => state.isType,
    getconfige: (state): any => state.confige,
    getToken: (state): string => state.token,
    getdataUser: (state): any => state.dataUser,
    getrouterInfo: (state): any => state.routerInfo,
    getstoreInfo: (state): any => state.storeInfo,
  },
  actions: {
    login(code: any) {
      loginByPwd(code).then((res: any) => {
        this.token = res.token;
        goodStorage.set('token',this.token);
        this.dataUser = res;
        goodStorage.set('dataUser',this.dataUser);
        uni.showToast({
          title: '登录成功',
          icon: 'none',
          duration: 1000,
        });
        const dataCan =  getURLParameters(goodStorage.get('locationUrl'))
        setTimeout(()=>{
          if (dataCan.zhibo_id) {
            window.location.href = location.href.split('?')[0] + '#/pages/live/zhibo?zhibo_id=' + dataCan.zhibo_id + '&inviter_code=' + res.invite_code
          } else if (dataCan.idcode) {
            window.location.href = location.href.split('?')[0] + '#/pages/shop/detail?idcode=' + dataCan.idcode + '&inviter_code=' + res.invite_code
          } else {
            window.location.href = location.href.split('?')[0] + '#/?inviter_code=' + res.invite_code
          }
          goodStorage.remove('locationUrl')
        },1000)
      });
    //   this.isLoggedIn = true;
    //   this.user = user;
    },
    setrouterInfo() {
      return this.routerInfo;
    },
    logout() {
      this.isLoggedIn = false;
      this.dataUser = null;
    },
    async getConfigeInfo() {
     confInfo().then((res:any)=>{
      this.confige = res
      goodStorage.set('configeInfo',res)
      })
    },
    changeType(){
      this.isType=!this.isType
      goodStorage.set('isType', this.isType)
    },
    async getUserInfo(){
      try {
        const res:any = await userInfo();
        goodStorage.set('dataUser', res);
        this.dataUser = res
        return res;
      }catch (error) {
        console.error('获取用户详情失败', error);
      }
     
    },
    async getStoreInfos(){
      try {
        let res:any = await selfInfo()
        goodStorage.set('storeInfo', res);
        this.storeInfo = res
        return res;
      }catch (error) {
        console.error('获取用户详情失败', error);
      }

    },
  },
});
